<template>
<div>
  <div v-if="modal">
    <Modal
      v-model="modal"
      width="1800"
      title="导入网格人员数据">
      <div>
        <Upload
          :loading="uploadLoading"
          :before-upload="handleBeforeUpload"
          action=""
          accept=".xls, .xlsx"
          type="drag">
          <div class="upload-tip">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>请导入.xls或.xlsx格式的Excel</p>
          </div>
        </Upload>
      </div>
      <Button type="primary" @click="importTableData" style="margin-bottom: 8px" :loading="buttinLodading">开始上传</Button>
      共计：{{tableData.length}} 条 | 成功：{{successNum}} 条 | 失败：{{failNum}} 条
      <Button type="error" style="margin-bottom: 8px" @click="findFailedList">查询上一次批量导入失败数据</Button>
      <template>
        <Progress :percent="schedule" :stroke-width="5">
          <Icon type="checkmark-circled"></Icon>
          <span v-if="schedule === 0">未开始</span>
          <span v-if="schedule >0 && schedule <100">{{schedule}}%</span>
          <span v-if="schedule === 100">成功</span>
        </Progress>
      </template>
      <div>
        <vxe-table
          v-if="showTableColumn"
          border
          align="center"
          highlight-hover-row
          height="400"
          :data="tableData">
          <template >
            <vxe-table-column width="20%"  v-for="(item,index) in columns" :key="index" :field="item.key" :fixed="item.fixed"  :title="item.title"></vxe-table-column>
          </template>
          <vxe-table-column width="10%"  field="import_type" title="导入状态" fixed="right">
            <template v-slot="{ row }">
              <span v-if="row.import_type === undefined">未导入</span>
              <span v-if="row.import_type === 'success'" style="color: #1E9FFF">导入成功</span>
              <span v-if="row.import_type === 'fail'" style="color: red">导入失败</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="30%" field="cause" title="失败原因" fixed="right"></vxe-table-column>
        </vxe-table>
      </div>
    </Modal>
    <Modal
      style="z-index: 1000;"
      width="700"
      v-model="failedModal"
      title="导入失败数据">
      <div style=" height: 400px;overflow: auto">
        共计 ：{{failedData.length}} 条
        <Table  stripe :columns="failedColumns" :data="failedData"></Table>
      </div>
    </Modal>
  </div>
</div>
</template>

<script>
import excel from '../../../../libs/excel'
import { findFailedList, importExcelInfo } from '../../../../api/eventlist'
import isNaN from 'xe-utils/methods'
// import { importExcelInfo } from '../../../../api/eventlist'

export default {
  name: 'import-tspeople-new',
  data () {
    return {
      uploadLoading: false,
      buttinLodading: false,
      showTableColumn: true,
      columns: [
        {
          align: 'center',
          title: '姓名',
          key: 'user_name'
        },
        {
          align: 'center',
          title: '身份证号',
          width: '160',
          key: 'cardno'
        },
        {
          align: 'center',
          title: '一级标签',
          width: '160',
          key: 'first_level_label'
        },
        {
          align: 'center',
          title: '二级标签',
          width: '160',
          key: 'second_level_label'
        }
      ],
      tableData: [],
      modal: false,
      failedModal: false,
      file: null,
      tableLoading: false,
      tableShow: true,
      schedule: 0,
      index: 0,
      successNum: 0,
      failNum: 0,
      failedColumns: [
        {
          type: 'index',
          align: 'center'
        },
        {
          title: '身份证号',
          key: 'cardno'
        },
        {
          title: '错误原因',
          key: 'message'
        },
        {
          title: '导入时间',
          key: 'create_time'
        }
      ],
      failedData: [],
      url: '/api/ac/grid/focusGroupService/saveImportUserFocusGroup',
      failedUrl: '/api/as/grid/userGrid/findTsNewFailedList'
    }
  },
  methods: {
    // // 初始化
    init () {
      this.modal = true
    },
    // 上传excel
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.tableData = []
        this.readFile(file)
        // this.getBase64(file)
        this.file = file
        console.log(file)
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 处理解析上传数据
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const { header, results } = excel.read(data, 'array')
        console.log(header)
        let resultData = this.$common.xeUtils.clone(results)
        this.tableData = resultData.slice(1)
        this.uploadLoading = false
        this.tableLoading = false
      }
    },
    async importTableData () {
      this.buttinLodading = true
      this.index = 0
      this.successNum = 0
      this.failNum = 0
      const uuid = this.uuid()
      for (let i = 0; i < this.tableData.length; i++) {
        if (i !== 0 && this.tableData[i].user_name === undefined && this.tableData[i].cardno === undefined) {
          this.tableData[i].user_name = this.tableData[i - 1].user_name
          this.tableData[i].cardno = this.tableData[i - 1].cardno
        }
        this.tableData[i].lid = uuid
        await importExcelInfo(this.url, this.tableData[i]).then(ret => {
          if (ret.data.errcode === 0) {
            this.tableData[i].import_type = 'success'
            this.showTableColumn = false
            this.$nextTick(function () {
              this.showTableColumn = true
            })
            this.index = this.index + 1
            this.successNum = this.successNum + 1
            this.schedule = this.GetPercent(this.index, this.tableData.length)
          } else {
            this.tableData[i].import_type = 'fail'
            this.tableData[i].cause = ret.data.errmsg
            this.showTableColumn = false
            this.$nextTick(function () {
              this.showTableColumn = true
            })
            this.index = this.index + 1
            this.failNum = this.failNum + 1
            this.schedule = this.GetPercent(this.index, this.tableData.length)
          }
          if (this.schedule === 100) {
            this.buttinLodading = false
          }
        }).catch(err => {
          console.log(err)
        })
      }
      console.log(this.tableData)
    },
    findFailedList () {
      findFailedList(this.failedUrl, '').then(ret => {
        if (ret.data.errcode === 0) {
          this.failedData = ret.data.data
          this.failedModal = true
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    GetPercent (num, total) {
      num = parseFloat(num)
      total = parseFloat(total)
      if (isNaN(num) || isNaN(total)) {
        return '-'
      }
      return total <= 0 ? '0%' : (Math.round(num / total * 10000) / 100.00)
    },
    uuid () {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-'

      var uuid = s.join('')
      return uuid
    }
  }
}
</script>

<style scoped>

</style>
